#!/usr/bin/env python

import re,sys,yaml
import os.path

dockerfileInFile = "Dockerfile.in"
metaFile = "origin-meta.yaml"

if len(sys.argv) > 1:
  dockerfileInFile =  sys.argv[1]
if len(sys.argv) > 2:
  metaFile =  sys.argv[2]

with open(dockerfileInFile, 'r') as f:
  dockerfileIn = f.read()

metaFile = os.path.join(os.path.dirname(dockerfileInFile), metaFile)
with open(metaFile, 'r') as f:
  metaYaml = yaml.safe_load(f)

froms = metaYaml['from']
if froms and len(froms) > 0:
  for base in froms:
    dockerfileIn = re.sub("FROM " + base['source'],"FROM " + base['target'],dockerfileIn)

envs = metaYaml['env']
if envs and len(envs) > 0:
  for base in envs:
    dockerfileIn = re.sub("ENV " + base['source'],"ENV " + base['target'],dockerfileIn)

#Remove aliases if only one is defined otherwise it will fail
aliases = []
froms = 0
for l in dockerfileIn.split("\n"):
  if l.startswith("FROM"):
    froms = froms + 1
    index = l.rfind("AS")
    if index > -1:
      aliases.append(l[index + 3:])
if len(aliases) == 1 and froms == 1:
  dockerfileIn = re.sub("--from=" + aliases[0],"",dockerfileIn)

exclude = False
print("### This is a generated file from Dockerfile.in ###")
for l in dockerfileIn.split('\n'):
  if l == "## EXCLUDE BEGIN ##":
    exclude = True
    continue
  if l == "## EXCLUDE END ##":
    exclude = False
    continue
  if not exclude:
    print(l)
